﻿// 途龙科技

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TcpServer;
/// <summary>
/// 公用方法类
/// </summary>
public static class ModbusDevicesHelp
{
    /// <summary>
    /// int转2个字节数组
    /// </summary>
    /// <param name="value"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    public static byte[] IntToByte(short value)
    {
        byte[] dst = new byte[2];
        return BitConverter.GetBytes(value);
    }
    /// <summary>
    /// 字节数组转字符串
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static string BytesToString(byte[] data)
    {
        if (data == null)
            return "";
        string dst = "";
        for (int i = 0; i < data.Length; i++)
        {
            dst += data[i].ToString("X2");
            if (i != data.Length - 1)
            {
                dst += " ";
            }
        }
        return dst;

    }
    /// <summary>
    /// 字节数组转浮点
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static float Byte16ToFloat(byte[] data)
    {
        if (data == null || data.Length == 0)
        {
            return 0;
        }
        string dst = "";
        for (int i = 0; i < data.Length; i++)
        {
            dst += data[i].ToString("X2");
            if (i != data.Length - 1)
            {
                // dst += " ";
            }
        }
        var dstint = int.Parse(dst, System.Globalization.NumberStyles.AllowHexSpecifier);
        return (float)dstint;
    }
    /// <summary>
    /// 字符串转字节数组
    /// </summary>
    /// <returns></returns>
    public static byte[] StringToBytes(string data)
    {
        var dst1 = data.Split(" ");
        byte[] dst = new byte[dst1.Length];
        for (int i = 0; i < dst1.Length; i++)
        {
            dst[i] = Convert.ToByte(dst1[i], 16);
        }
        return dst;
    }
    /// <summary>
    /// IEEE754解析
    /// </summary>
    /// <param name="datas"></param>
    /// <returns></returns>
    public static float IEEE754ToFloat(Byte[] datas)
    {
        string data = BytesToString(datas);

        UInt32 X = Convert.ToUInt32(data.Replace(" ", ""), 16);
        // X= BitConverter.ToUInt32(datas);
        return BitConverter.ToSingle(BitConverter.GetBytes(X), 0);
    }
    /// <summary>
    /// 输出
    /// </summary>
    public static void ConsoleWrite(string mess, bool isWrite,
        ConsoleColor color = ConsoleColor.White)
    {
        if (!isWrite)
        {
            return;
        }
        if (Console.ForegroundColor != color)
        {
            Console.ForegroundColor = color;
        }
        Console.WriteLine(DateTime.Now.ToString() + " " + mess);
        if (Console.ForegroundColor != ConsoleColor.White)
        {
            Console.ForegroundColor = ConsoleColor.White;
        }
    }
}
